﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mshtml;
using System.IO;

namespace Webparshing
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ComboControl comboct = new ComboControl();

        private void buttonWebbrowserGo_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textBoxWebbrowserUrl.Text);
        }

        private void buttonFormRecive_Click(object sender, EventArgs e)
        {
            mshtml.HTMLDocument HTMLDoc = new HTMLDocument();
            HTMLDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
            
            for (int i = 0; i < dataGridViewFormObjects.Rows.Count-1; i++)
            {
                if (dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString().Length > 0)
                {
                    IHTMLElement formobject = (IHTMLElement)HTMLDoc.getElementsByName(dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString()).item(null, 0);
                    dataGridViewFormObjects.Rows[i].Cells[1].Value = formobject.getAttribute("value");
                }
            }
        }

        private void buttonFillForm_Click(object sender, EventArgs e)
        {
            mshtml.HTMLDocument HTMLDoc = new HTMLDocument();
            HTMLDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;

            for (int i = 0; i < dataGridViewFormObjects.Rows.Count-1; i++)
            {
                if (dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString().Length > 0)
                {
                    IHTMLElement formobject = (IHTMLElement)HTMLDoc.getElementsByName(dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString()).item(null, 0);
                    formobject.setAttribute("value", dataGridViewFormObjects.Rows[i].Cells[1].Value,0);
                }
            }
        }

        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            HhmlParser HtmlParse = new HhmlParser();
            string parmeterString = string.Empty;
            for (int i = 0; i < dataGridViewFormObjects.Rows.Count-1; i++)
            {
                if (dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString().Length > 0)
                {
                    parmeterString += dataGridViewFormObjects.Rows[i].Cells[0].Value.ToString() + "=" + dataGridViewFormObjects.Rows[i].Cells[1].Value.ToString() + "&";
                }
            }
 
            HtmlParse.HttpWebResponseFormPost(webBrowser1, textBoxFormAction.Text.ToString(), parmeterString);
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            tabControl1.SelectTab(tabPage1);

            HhmlParser HtmlParse = new HhmlParser();

            Stream docStream = webBrowser1.DocumentStream;

            StreamReader docStreamReader = new StreamReader(docStream, System.Text.Encoding.GetEncoding(webBrowser1.Document.Encoding));
            docStream.Position = 0;

            textBoxWebSource.Text = docStreamReader.ReadToEnd();

            comboBoxFormName.Items.Clear();
            comboBoxFormName.ResetText();
            textBoxFormAction.ResetText();
            dataGridViewFormObjects.Rows.Clear();
            dataGridViewValueSelect.Rows.Clear();
            textBoxOuterHTML.Text = webBrowser1.Document.Body.OuterHtml;

            IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
            IHTMLElementCollection forms = doc.forms;
            foreach (HTMLFormElement form in forms)
            {
                if (form.name != null)
                    comboct.AddComboItem(ref comboBoxFormName, form.name, form.name);
            }

       }

        private void textBoxWebbrowserUrl_Enter(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textBoxWebbrowserUrl.Text);
        }

        private void buttonEx_Click(object sender, EventArgs e)
        {
            string Exmethod = comboBoxExmethod.Text.ToString();
            string Attribute = comboBoxAttribute.Text.ToString();
            for (int i = 0; i < dataGridViewValueSelect.Rows.Count-1; i++)
            {
                string searchText = dataGridViewValueSelect.Rows[i].Cells[0].Value.ToString();
                string subMethod = "0";
                if (dataGridViewValueSelect.Rows[i].Cells[1].Value != null) subMethod = dataGridViewValueSelect.Rows[i].Cells[1].Value.ToString();
                if (Exmethod == "아이디(GetElementById)")
                {
                    HtmlDocument doc = null;
                    doc = webBrowser1.Document;
                    if (Attribute == "GetAttribute()")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = doc.GetElementById(searchText).GetAttribute(subMethod).ToString();
                        dataGridViewValueSelect.Rows[i].Cells[3].Value = doc.GetElementById(searchText).GetAttribute(subMethod).Length;
                    }
                    else if (Attribute == "innerText")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = doc.GetElementById(searchText).InnerText.ToString();
                    }
                    else if (Attribute == "innerHtml")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = doc.GetElementById(searchText).InnerHtml.ToString();
                    }
                    else if (Attribute == "outerHtml")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = doc.GetElementById(searchText).OuterHtml.ToString();
                    }
                    else if (Attribute == "outerText")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = doc.GetElementById(searchText).OuterText.ToString();
                    }
                }
                else if (Exmethod == "아이디(getElementById)")
                {
                    mshtml.HTMLDocument HTMLDoc = new HTMLDocument();
                    HTMLDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
                    if (Attribute == "GetAttribute()")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementById(searchText).getAttribute(subMethod).ToString();
                    }
                    else if (Attribute == "innerText")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementById(searchText).innerText.ToString();
                    }
                    else if (Attribute == "innerHtml")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementById(searchText).innerHTML.ToString();
                    }
                    else if (Attribute == "outerHtml")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementById(searchText).outerHTML.ToString();
                    }
                    else if (Attribute == "outerText")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementById(searchText).outerText.ToString();
                    }                    
                }                
                else if (Exmethod == "이름(getElementsByName)")
                {
                    mshtml.HTMLDocument HTMLDoc = new HTMLDocument();
                    HTMLDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
                    if (Attribute == "GetAttribute()")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementsByName(searchText).ToString();
                        dataGridViewValueSelect.Rows[i].Cells[3].Value = HTMLDoc.getElementsByName(searchText).length.ToString();
                    }
                }
                else if (Exmethod == "태그명(GetElementsByTagName)")
                {
                    HtmlDocument doc = null;
                    doc = webBrowser1.Document;
                    if (Attribute == "GetAttribute()")
                    {
                        dataGridViewValueSelect.Rows[i].Cells[3].Value = doc.GetElementsByTagName(searchText).Count; 
                        for (int k = 0; k < doc.GetElementsByTagName(searchText).Count; k++)
                        {
                            dataGridViewValueSelect.Rows[i].Cells[2].Value += doc.GetElementsByTagName(searchText)[k].GetAttribute(subMethod).ToString() + "\n\r";
                        }
                    }
                }
                else if (Exmethod == "태그명(getElementsByTagName)")
                {
                    mshtml.HTMLDocument HTMLDoc = new HTMLDocument();
                    HTMLDoc = (mshtml.HTMLDocument)webBrowser1.Document.DomDocument;
                    dataGridViewValueSelect.Rows[i].Cells[2].Value = HTMLDoc.getElementsByTagName(searchText).ToString();
                    dataGridViewValueSelect.Rows[i].Cells[3].Value = HTMLDoc.getElementsByTagName(searchText).length.ToString();
                }
                else if (Exmethod == "태그제거파싱라인(GetHtmlString)")
                {
                    HhmlParser HtmlParse = new HhmlParser();
                    string strURL = webBrowser1.Url.ToString();
                    string txtHtml = HtmlParse.GetHtmlString(strURL);

                    String[] SplitStr = txtHtml.Split(':');
                    int count = 0;
                    int addCount = 0;
                    if(Int32.TryParse(dataGridViewValueSelect.Rows[i].Cells[3].Value.ToString(), out addCount))
                    {
                        addCount = Int32.Parse(dataGridViewValueSelect.Rows[i].Cells[3].Value.ToString());
                    }
                    foreach (String s in SplitStr)
                    {
                        if (s.IndexOf(searchText) > -1)
                        {
                            dataGridViewValueSelect.Rows[i].Cells[2].Value = SplitStr[count + addCount].ToString().Replace("\r", "");
                            break;
                        }
                        count++;
                    }
                }
                else if (Exmethod == "태그제거파싱라인_br제거(GetHtmlStringWihtBrChangePipe)")
                {
                     HhmlParser HtmlParse = new HhmlParser();
                    string txtHtml = HtmlParse.GetHtmlStringWihtBrChangePipe(textBoxWebSource.Text);
                    String[] SplitStr = txtHtml.Split(':');
                    int count = 0;
                    int addCount = 0;
                    if (Int32.TryParse(subMethod, out addCount))
                    {
                        addCount = Int32.Parse(subMethod);
                    }
                    foreach (String s in SplitStr)
                    {
                        if (s.IndexOf(searchText) > -1)
                        {
                            dataGridViewValueSelect.Rows[i].Cells[2].Value = SplitStr[count + addCount].ToString().Replace("\r", "");
                            break;
                        }
                        count++;
                    }
               }
                else if (Exmethod == "스타일(className)")
                {
                }
                else if (Exmethod == "이미지(webdocument.images)")
                {
                }
                else if (Exmethod == "링크(webdocument.links)")
                {
                }
                else if (Exmethod == "폼액션(action)")
                {
                }
                else if (Exmethod == "프레임(frames)")
                {
                }        

            }
        }

        private void textBoxWebbrowserUrl_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) textBoxWebbrowserUrl_Enter(sender, e);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            HhmlParser HtmlParse = new HhmlParser();
            IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
            if (tabControl1.SelectedTab == tabPage2)
            {
                textBoxTagRemoved.Text = HtmlParse.GetHtmlString(webBrowser1.Url.ToString());
            }
            else if (tabControl1.SelectedTab == tabPage3)
            {
                textBoxBrTag.Text = HtmlParse.GetHtmlStringWihtBrChangePipe(textBoxWebSource.Text);
            }
            else if (tabControl1.SelectedTab == tabPage4)
            {
                IHTMLElementCollection allElements = doc.images;
                dataGridViewImages.Rows.Clear();
                foreach (IHTMLImgElement img in allElements)
                {
                    string alt = string.Empty;
                    if (img.alt != null) alt = img.alt.ToString();
                    string[] Newrow = { img.src.ToString(), img.nameProp.ToString(), img.mimeType.ToString(), img.width.ToString(), img.height.ToString(), alt };
                    dataGridViewImages.Rows.Add(Newrow);
                }
            }
            else if (tabControl1.SelectedTab == tabPage5)
            {
                listBoxLinks.Items.Clear();
                IHTMLElementCollection links = doc.links;
                foreach (IHTMLElement link in links)
                {
                    listBoxLinks.Items.Add(link.getAttribute("href"));
                }
            }
            else if (tabControl1.SelectedTab == tabPage6)
            {
                listBoxForms.Items.Clear();
                IHTMLElementCollection forms = doc.forms;
                foreach (HTMLFormElement form in forms)
                {
                   if(form.name != null)
                    listBoxForms.Items.Add(form.name);                    
                }
            }
        }

        private void comboBoxFormName_SelectedValueChanged(object sender, EventArgs e)
        {
            dataGridViewFormObjects.Rows.Clear();
            string selectedForm = comboct.GetComboText(ref comboBoxFormName);
            IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
            string domain = doc.domain.ToString();
            IHTMLElementCollection forms = doc.forms;
            foreach (IHTMLFormElement form in forms)
            {
                if (form.name != null && form.name == selectedForm)
                {
                    if(form.action != null) textBoxFormAction.Text = domain + form.action.ToString();
                    foreach (IHTMLElement el in form.elements)
                    {                 
                        if (el.GetType().ToString() == "mshtml.HTMLInputElementClass")
                        {
                            IHTMLInputElement input = (IHTMLInputElement)el;
                            string inputname = string.Empty;
                            string inputvalue = string.Empty;
                            if (input.name != null) inputname = input.name.ToString();
                            if (input.value != null) inputvalue = input.value.ToString();
                            string[] Newrow = { inputname, inputvalue };
                            dataGridViewFormObjects.Rows.Add(Newrow);
                        }
                        
                    }
                }
                    
            }
           
        }

        private void buttonSubmitClick_Click(object sender, EventArgs e)
        {
            string selectedForm = comboct.GetComboText(ref comboBoxFormName);
            webBrowser1.Document.Forms[selectedForm].InvokeMember("submit");
        }

        private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            textBoxWebbrowserUrl.Text = webBrowser1.Url.ToString();
        }

        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            textBoxNewWin.Text = sender.ToString();
        }

        private void buttonDown_Click(object sender, EventArgs e)
        {
            Login_Auction();
            webBrowser1.Navigate("http://www.esmplus.com/Escrow/Delivery/GeneralDeliveryExcel?siteGbn=0&searchAccount=6640&searchDateType=PAD&searchSDT=2012-09-15&searchEDT=2012-12-15&searchKey=ON&searchKeyword=&searchStatus=0&searchAllYn=Y&splitYn=no");
        }

        private void buttonInterpark_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://ipss.interpark.com/delivery/ProOrderCheckList.do?_method=excelDown");
        }

        private void buttonStreet11_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://soffice.11st.co.kr/escrow/OrderingLogisticsAction.tmall?method=getLogisticsForExcel&isItalyAgencyYn=&isAbrdSellerYn=&listType=orderingLogistics");
        }

        private void buttonShopN_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate("https://order.sell.shop.naver.com/sale/delivery/spreadsheet/xls?summaryInfoType=NEW_ORDERS&sort.type=RECENTLY_ORDER_YMDT&rowPerPageType=ROW_CNT_100&paging.current=1");
        }

        private void Login_Auction()
        {
            string GoUrl = "https://www.esmplus.com/SignIn/Authenticate";
            HhmlParser HtmlParse = new HhmlParser();
            HtmlParse.HttpWebResponseFormPost(webBrowser1, GoUrl, "Type=S&ReturnUrl=&SiteType=GMKT&Id=eminong&Password=wlakzpt01");
        }

    }
}
